using Comteck.Ktt.Services;
using log4net;
using System;
using System.Configuration;
using System.Data.Entity;
using System.IO;

namespace Comteck.TenantSystem.Services {
  /// <summary>
  /// 本地数据库集合
  /// </summary>
  public class LocalDbContainer {
    /// <summary>
    /// 日志
    /// </summary>
    public static ILog Logger = LogManager.GetLogger(typeof(LocalDbContainer));

    /// <summary>
    /// 
    /// </summary>
    static LocalDbContainer() {
      // 设置DataDirectory到应用程序目录下的data文件夹
      var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
      var dataDirectory = Path.Combine(baseDirectory, "data");
      AppDomain.CurrentDomain.SetData("DataDirectory", dataDirectory);

      // 确保data目录存在
      if (!Directory.Exists(dataDirectory)) {
        Directory.CreateDirectory(dataDirectory);
      }

      // 检查及修复数据库异常
      RepairDB();

      // 加载数据库到内存
      LoadDB();
    }

    /// <summary>
    /// 检查及修复数据库异常
    /// </summary>
    private static void RepairDB() {
      var basePath = System.AppDomain.CurrentDomain.BaseDirectory;
      var sqlite = System.IO.Path.Combine(basePath, "sqlite3.exe");
      if (!File.Exists(sqlite)) {
        return;
      }

      RepairDBOne(sqlite, basePath);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sqlite"></param>
    /// <param name="enumDbType"></param>
    private static void RepairDBOne(string sqlite, string basePath) {
      var connstr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
      var dbName = connstr.Substring(connstr.IndexOf("\\") + 1, connstr.IndexOf(";") - connstr.IndexOf("\\") - 1);

      var dbFile = $"{AppDomain.CurrentDomain.GetData("DataDirectory").ToString()}\\{dbName}";
      try {
        // 文件不存在
        if (!File.Exists(dbFile)) {
          return;
        }

        var isFileOk = SqliteRepairHelper.IsDbFileOk(sqlite, dbFile);
        if (!isFileOk) {
          SqliteRepairHelper.Repair(sqlite, dbFile);
          Logger.Info($"{dbFile} repair success");
        }
      } catch (Exception ex) {
        Logger.Error($"{dbFile} repair error", ex);
      }
    }

    /// <summary>
    /// LoadDB
    /// </summary>
    private static void LoadDB() {
      Database.SetInitializer(new MigrateDatabaseToLatestVersion<AppDbContext, MigratorConfiguration>());
    }

    /// <summary>
    /// 初始化
    /// </summary>
    public static void Init() {
    }

    /// <summary>
    /// 
    /// </summary>
    public static void Dispose() {
    }

  }
}
